﻿namespace Max.PH6_2009A.LowCode.API.Auth
{
    public class JwtAuth
    {
        JwtConfig _config;
        public JwtAuth(JwtConfig config)
        {
            _config = config;
        }

        public string CreateToken(TokenType type)
        {
            byte[] byts = System.Text.Encoding.UTF8.GetBytes(type == TokenType.Token ? _config.Key : _config.RefleshKey);
            Microsoft.IdentityModel.Tokens.SecurityKey key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(byts);
            Microsoft.IdentityModel.Tokens.SigningCredentials credentials =
                  new Microsoft.IdentityModel.Tokens.SigningCredentials(key, "HS256");

            //SecurityToken是抽象类，不能直接实例化 System.
            Microsoft.IdentityModel.Tokens.SecurityToken st = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                issuer: _config.Issure, //签发人，发行人
                audience: _config.Audience, //受众
                claims: null, //声明
                notBefore: null, //生效时间
                expires: System.DateTime.Now.AddMinutes(type == TokenType.Token ? _config.Expires : _config.RefleshExpires), //过期时间
                signingCredentials: credentials  //签名凭证
                );
            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(st);

            return token;
        }
    }

    public class JwtConfig
    {
        public string Issure { get; set; }
        public string Audience { get; set; }
        public int Expires { get; set; }
        public string Key { get; set; }
        public int RefleshExpires { get; set; }
        public string RefleshKey { get; set; }


        public JwtConfig(IConfiguration config)
        {
            this.Issure = config.GetSection("Jwt:Issure").Value;
            this.Audience = config.GetSection("Jwt:Audience").Value;
            this.Expires = Convert.ToInt32(config.GetSection("Jwt:Expires").Value);
            this.Key = config.GetSection("Jwt:Key").Value;
            this.RefleshExpires = Convert.ToInt32(config.GetSection("Jwt:RefleshExpires").Value);
            this.RefleshKey = config.GetSection("Jwt:RefleshKey").Value;
        }
    }

    public enum TokenType
    {
        /// <summary>
        /// 正常用的
        /// </summary>
        Token,

        /// <summary>
        /// 刷新token
        /// </summary>
        RefleshToken,
    }
}
